<template>
  <div class="home">
    <!-- <img alt="Vue logo" src="../assets/logo.png" /> -->
    <!-- <HelloWorld msg="Welcome to Your Vue.js App" /> -->
    <div class="border">
      <!-- 拖拽上传 -->
      <el-upload
        ref="upload"
        class="upload-demo"
        show-file-list
        action="https://jsonplaceholder.typicode.com/posts/"
        :drag="true"
        :on-change="handleChange"
        :limit="1"
        :auto-upload="false"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <!-- 按钮上传 -->
      <!-- <el-upload
        class="upload-demo"
        ref="upload"
        action="https://jsonplaceholder.typicode.com/posts/"
        :limit="1"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :auto-upload="false">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload> -->
      <el-button type="primary" style="margin-top: 50px" @click="startDeal()"
        >开始处理</el-button
      >
    </div>
  </div>
</template>

<script>
// @ is an alias to /src
// import HelloWorld from "@/components/HelloWorld.vue";
import * as XLSX from "xlsx";

export default {
  name: "Home",
  components: {
    // HelloWorld,
  },
  data() {
    return {
      originData: [], // 原始表格数据
      originName: "", // 文件名
    };
  },
  methods: {
    handleChange(file) {
      console.log("file ===> ", file);
      // console.log('fileList ===> ', fileList)
      this.originName = file.name.split(".")[0];
      this.readExcel({ 0: file.raw });
      // this.readFile(file.raw);
    },
    readExcel(files) {
      // 表格导入
      if (files.length <= 0) {
        // 如果没有文件名
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$Message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }
      const fileReader = new FileReader();
      fileReader.onload = (files) => {
        try {
          const data = files.target.result;
          const workbook = XLSX.read(data, {
            type: "binary",
          });
          const wsname = workbook.SheetNames[0]; // 取第一张表
          console.log("wsname ----->", wsname, workbook);
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); // 生成json表格内容
          console.log(ws, "ws是表格里的数据，且是json格式");
          this.originData = ws;
          // 重写数据
          this.$refs.upload.value = "";
          // return ws
        } catch (e) {
          console.log(e);
          return false;
        }
      };
      fileReader.readAsBinaryString(files[0]);
    },
    generateRandomString(length) {
      // 生成随机字符串
      const characters =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
      return Array.from({ length })
        .map(() =>
          characters.charAt(Math.floor(Math.random() * characters.length))
        )
        .join("");
    },
    startDeal() {
      /**
       * 处理文件，给答案加密，abcd对应0123，加密后放在第10位(在数组中下标为9)
       * 前四位固定为 "yzsy",后面加5位随机字符串，加答案对应的数字，后面加4位随机字符串
       * 例如答案为d，加密后示例：yszyh8ui3km17b
       * */
      console.log(this.originName + "_yzsy");
      const dict = ["a", "b", "c", "d", "A", "B", "C", "D"];
      let pswStart,
        pswEnd,
        ans = "";
      try {
        this.originData.forEach((item) => {
          if (!item.type) {
            // 检查文件内容中是否包含type，如果没有抛出错误。
            console.log("no error??", item.type);
            throw new Error("文件格式错误");
          }
          if (item.type == "选择" || item.type == "判断") {
            // 给选择、判读的答案加密
            ans = dict.findIndex((opt) => opt == item.code);
            ans = ans > 3 ? ans - 4 : ans;
            if (ans < 0) throw new Error("答案有误");
            pswStart = this.generateRandomString(5);
            pswEnd = this.generateRandomString(4);
            console.log("ans => ", ans, pswStart, pswEnd);
            item.code = "yzsy" + pswStart + ans + pswEnd;
          }
        });
        console.log("deal success => ", this.originData);
        this.exportToExcel(this.originData, this.originName + "_yzsy");
      } catch (error) {
        console.log("文件处理error =>", error);
        this.$message({
          message: "文件处理出错！请仔细检查文件内容，或联系吕政均。",
          type: "error",
        });
      }
      // this.exportToExcel(this.originData, this.originName + '_yzsy')
    },
    exportToExcel(data, fileName) {
      // 导出
      // 将数据转换为工作表
      const worksheet = XLSX.utils.json_to_sheet(data);
      // 创建工作簿并添加工作表
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
      // 生成Excel文件
      const excelBuffer = XLSX.write(workbook, {
        bookType: "xlsx",
        type: "array",
      });
      // 创建Blob对象
      const dataBlob = new Blob([excelBuffer], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8",
      });
      // 创建链接并模拟点击下载
      const downloadLink = document.createElement("a");
      downloadLink.href = window.URL.createObjectURL(dataBlob);
      downloadLink.download = fileName + ".xlsx";
      document.body.appendChild(downloadLink);
      downloadLink.click();
      document.body.removeChild(downloadLink);
    },
  },
};
</script>
<style lang="less" scoped>
.border {
  margin: 100 auto;
  text-align: center;
  padding: 50px 100px;
  margin-top: 100px;
}
</style>
